package base.recycleview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.net.http.SslError;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aliang.auto.R;
import com.bumptech.glide.Glide;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.WebViewClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import app.auto.AndroidInstance;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.utility.BackStack;

public class RecycleViewUtil extends AndroidInstance {

    public static final String KEY_IMAGE = "image";
    public static final String KEY_TXT = "txt";

    private View displayview;

    int itemid;
    int imageid;
    private float spaceitem = 3;
    private FunCallback funCallback;

    public RecycleViewUtil setSpaceitem(float spaceitem) {
        this.spaceitem = spaceitem;
        return this;
    }

    public RecycleViewUtil setItemid(int itemid) {
        this.itemid = itemid;
        return this;
    }

    public RecycleViewUtil setImageid(int imageid) {
        this.imageid = imageid;
        return this;
    }


    private int parentid;

    public RecycleViewUtil setParentid(int parentid) {
        this.parentid = parentid;
        return this;
    }

    public RecycleViewUtil setDisplayview(View displayview) {
        this.displayview = displayview;
        displayview.setOnClickListener(new View.OnClickListener() {
            int lastPostion;

            @Override
            public void onClick(View view) {
//                variedlasttimes++;
                if (!imageIsGrid) {
                    ((ImageView) view).setImageResource(R.mipmap.grid);
                } else {
                    ((ImageView) view).setImageResource(R.mipmap.list);
                }
                imageIsGrid = !imageIsGrid;
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    lastPostion = ((GridLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
                    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                } else {
                    lastPostion = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
                    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
                }

//                data.clear();
//                data.addAll(set);
//                recyclerView.removeAllViews();
//                radapter.notifyDataSetChanged();
                recyclerView.setAdapter(radapter);
                recyclerView.scrollToPosition(lastPostion);
            }
        });
        return this;
    }

    RecyclerView.Adapter radapter;
    String path = null;


    List<Map> data = new ArrayList<Map>();

    public RecycleViewUtil setData(List<Map> data) {
        this.data = data;
        return this;
    }

    int variedlasttimes = 0;
    int variednow = 0;

    boolean imageIsGrid = true;
    private RecyclerView recyclerView;

    public RecycleViewUtil setRecyclerView(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        return this;
    }


    private ThreadPoolExecutor pool;

    public RecyclerView get() {

//        findViewById(R.id.image_back).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

//        findViewById(R.id.image_edit).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                IntentUtil.get(IntentUtil.class, v.getContext()).startActy(v.getContext(), ImageEditActivity.class.getName(), MapBuilder.build()
//                        .add("data", init())
//                        .get());
//            }
//        });
//        findViewById(R.id.image_setup).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                IntentUtil.get(IntentUtil.class, v.getContext()).startActy(v.getContext(), SetupActivity.class.getName());
//            }
//        });
//        findViewById(R.id.image_transfer).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                v.getContext().startActivity(new Intent(v.getContext(), ImageTransferActivity.class));
//
////                IntentUtil.startActy(v.getContext(), ImageTransferActivity.class.getName(), MapBuilder.build().add("data", init()).get());
//            }
//        });
//        findViewById(R.id.image_del).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ShareAlert.delAlert((Activity) v.getContext(), 20, new FunCallback() {
//                    @Override
//                    public void simpleRun(Object aty, Object... p) {
//                        super.simpleRun(aty, p);
//                        File file = data.get(selectedpos);
//                        file.delete();
//
//                        data.remove(selectedpos);
//                        radapter.notifyItemRemoved(selectedpos);
//                        radapter.notifyItemChanged(selectedpos);
//                    }
//                });
//
//
//            }
//        });

//        String pathopt = (String) SPrefUtil.getValue(LocalCache.SETUP_IMAGEPATH);
//
//        path = Util.getImagePath(pathopt, getActivity());
//        new File(path).mkdirs();


        recyclerView.addItemDecoration(new SpacesItemDecoration((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, spaceitem, getContext().getResources().getDisplayMetrics())));


        radapter = new RecyclerView.Adapter() {
            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                View view = null;
                if (imageIsGrid) {
                    view = LayoutInflater.from(getActivity()).inflate(itemid, null);
//                    view.setTag(R.id.item_list, false);

                } else {
                    view = LayoutInflater.from(getActivity()).inflate(R.layout.rv_list_item, null);
//                    view.setTag(R.id.item_list, true);
                }
                return new RecyclerView.ViewHolder(view) {

                };
            }


            @SuppressLint("NewApi")
            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                final Map map = (Map) data.get(position);

                if (variedlasttimes != variednow) {
                    holder = null;
                    holder = onCreateViewHolder(null, -1);
                    variednow = variedlasttimes;
                }
//                if (imageIsGrid) {
//                    if ((Boolean) holder.itemView.getTag(R.id.item_list)) {
//                        holder = new RecyclerView.ViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.rv_grid_item, null)) {
//                        };
//                        holder.itemView.setTag(R.id.item_list, false);
//
//                    }
//                } else {
//                    if (!(Boolean) holder.itemView.getTag(R.id.item_list)) {
//                        holder = new RecyclerView.ViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.rv_list_item, null)) {
//                        };
//                        holder.itemView.setTag(R.id.item_list, true);
//
//                    }
//                }

                Object oimage = map.get("image");

                if (oimage instanceof String) {
                    String image = (String) oimage;
                    try {
                        if (!TextUtils.isEmpty(image)) {
                            holder.itemView.findViewById(imageid).setVisibility(View.VISIBLE);
                            Glide.with(getActivity()).load(image).into(((ImageView) holder.itemView.findViewById(imageid)));

                        } else {
                            holder.itemView.findViewById(imageid).setVisibility(View.GONE);

                        }
                    } catch (Exception e) {
//                    ShareAlert.shareAlert(getActivity(), e.getCause() + " " + e.getMessage());
                    }


                } else {
                    int image = (int) oimage;
                    try {
                        if (image != -1) {
                            holder.itemView.findViewById(imageid).setVisibility(View.VISIBLE);
                            Glide.with(getActivity()).load(image).into(((ImageView) holder.itemView.findViewById(imageid)));

                        } else {
                            holder.itemView.findViewById(imageid).setVisibility(View.GONE);

                        }
                    } catch (Exception e) {
//                    ShareAlert.shareAlert(getActivity(), e.getCause() + " " + e.getMessage());
                    }
                }
                String txt = (String) map.get("txt");
                if (TextUtils.isEmpty(txt)) {
                    txt = (String) map.get("text");
                }
                if (!TextUtils.isEmpty(txt)) {
                    holder.itemView.findViewById(R.id.text_item).setVisibility(View.VISIBLE);
                    ((TextView) holder.itemView.findViewById(R.id.text_item)).setText(txt);
                } else {
                    holder.itemView.findViewById(R.id.text_item).setVisibility(View.GONE);

                }
                if (position == selectedpos) {
                    holder.itemView.setForeground(ContextCompat.getDrawable(getActivity(), R.drawable.auto_background_rect_white));
                } else {
                    holder.itemView.setForeground(null);
                }
                if (!imageIsGrid) {
                    if (holder.itemView.getLayoutParams() == null) {
                        holder.itemView.setLayoutParams(new ViewGroup.MarginLayoutParams(-1, -2));
                    } else
                        holder.itemView.getLayoutParams().width = -1;
                }

                if (!TextUtils.isEmpty((CharSequence) map.get("link"))) {
                    ImageView iv = holder.itemView.findViewById(imageid);
                    imageOnTouch(map, iv,parentid);


                }
            }



            @Override
            public int getItemCount() {
                return data.size();
            }
        };
        recyclerView.setAdapter(radapter);
        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
            View focus;

            @Override
            public void onItemClick(View view, int position) {
                selectedpos = position;
//                if (focus == null) {
//                    view.setTag(R.id.item_focus, true);
//                    focus = view;
//                } else {
//                    focus.setTag(R.id.item_focus, null);
//                    view.setTag(R.id.item_focus, true);
//                    focus = view;
//                }
//                selected = position;
                radapter.notifyDataSetChanged();
            }
        }));
        return recyclerView;
    }

    private Context getActivity() {
        return getContext();
    }


    int selectedpos;

    public static void imageOnTouch(final Map map, ImageView iv, final int webcontainerid) {
        final Activity getActivity = (Activity) iv.getContext();
        iv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AgentWebConfig.debug();
                @SuppressLint("ClickableViewAccessibility") final AgentWeb.PreAgentWeb agentWeb = AgentWeb.with((Activity) getActivity)//这里需要把 Activity 、 和 Fragment  同时传入
                        .setAgentWebParent((((ViewGroup) ((Activity) getActivity).findViewById(webcontainerid))), new RelativeLayout.LayoutParams(-1, -1))// 设置 AgentWeb 的父控件 ， 这里的view 是 LinearLayout ， 那么需要传入 LinearLayout.LayoutParams
                        .useDefaultIndicator()// 使用默认进度条\
                        .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                        .setWebViewClient(new WebViewClient())
//                                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //注意这里开启 strict 模式 ， 设备低于 4.2 情况下回把注入的 Js 全部清空掉 ， 这里推荐使用 onJsPrompt 通信
                        .createAgentWeb().ready();//

//                            agentWeb.get().getWebCreator().getWebView().setOnKeyListener(new View.OnKeyListener() {
//                                @Override
//                                public boolean onKey(View v, int keyCode, KeyEvent event) {
//                                    if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                                        if (keyCode == KeyEvent.KEYCODE_BACK && agentWeb.get().getWebCreator().getWebView().canGoBack()) { // 表示按返回键时的操作
//                                            agentWeb.get().getWebCreator().getWebView().goBack(); // 后退
//                                            // webview.goForward();//前进
//                                            return true; // 已处理
//                                        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
//                                            WebView wv = agentWeb.get().getWebCreator().getWebView();
//                                            ((RelativeLayout) wv.getParent()).removeAllViews();
//                                            ((RelativeLayout) wv.getParent()).setVisibility(View.GONE);
//                                            ((Activity) getActivity).onKeyDown(keyCode,event);
//                                            return true; // 已处理
//                                        }
//                                    }
//                                    return false;
//                                }
//                            });


                agentWeb.go((String) map.get("link"));
//                ((Activity) getActivity).findViewById(webcontainerid).setVisibility(View.VISIBLE);
//
//
//                ((BackStack) BackStack.map((Activity) getActivity)).onClickRun(new FunCallback() {
//                    @Override
//                    public void onCallback(Object result, Object object) {
//                        super.onCallback(result, object);
//
//                        if (agentWeb.get().getWebCreator().getWebView().canGoBack()) {
//                            agentWeb.get().getWebCreator().getWebView().goBack();
//                            return;
//                        }
//                        if (((Activity) getActivity).findViewById(webcontainerid).getVisibility() == View.GONE) {
//                            ((Activity) getActivity).finish();
//                            return;
//                        }
//                        ((Activity) getActivity).findViewById(webcontainerid).setVisibility(View.GONE);
////                                    ((Activity) getActivity).findViewById(R.id.bar).setVisibility(View.GONE);
//
//                        agentWeb.get().destroy();
////                                    urls.clear();
////                                    new Handler(Looper.getMainLooper(), new Handler.Callback() {
////                                        @Override
////                                        public boolean handleMessage(@NonNull Message message) {
////                                            if (radapter != null) {
////                                                radapter.notifyDataSetChanged();
////                                            }
////                                            return false;
////                                        }
////                                    }).sendEmptyMessage(0);
//
//                    }
//                });
                return true;
            }
        });
    }


    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }

    public RecycleViewUtil setClick(FunCallback funCallback) {
        this.funCallback = funCallback;
        return this;
    }


    public static class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;

            // Add top margin only for the first item to avoid double space between items
//            if (parent.getChildPosition(view) == 0)
            outRect.top = space;
        }
    }



}
